package cn.topcodes.tcsf.cms.web.controller;

import cn.topcode.unicorn.utils.FileUtil;
import cn.topcodes.tcsf.cms.service.ConfigService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by yvan
 * Author: Yvan
 * Date: 2017/12/29
 * Time: 上午10:04
 **/

@Controller
@RequestMapping("/admin/other/")
public class OtherController {


    public static final String FILE_PATH = "/admin/other/dl-image";

    public static final String FILEVIDEO_PATH = "/admin/other/dl-video";

    @Autowired
    private ConfigService configService;

    @RequestMapping(value = "dl-image", method = RequestMethod.GET)
    public void downloadImg(@RequestParam(required = true) String path, HttpServletResponse response) throws IOException {
        String filepath = configService.getFileFolderPath() + path;
        File file = new File(filepath);
        if (!file.exists()) {
            response.sendError(HttpStatus.SC_NOT_FOUND);
            return;
        }
        FileInputStream fin = new FileInputStream(file);
        try {
            IOUtils.copy(fin, response.getOutputStream(), 1024);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "dl-video", method = RequestMethod.GET)
    public void downloadVideo(@RequestParam(required = true) String path, HttpServletResponse response) throws IOException {
        String filepath = configService.getFileFolderPath() + path;
        File file = new File(filepath);
        if (!file.exists()) {
            response.sendError(HttpStatus.SC_NOT_FOUND);
            return;
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName()));
        response.addHeader("Content-Length", "" + file.length());
        FileInputStream fin = new FileInputStream(file);
        try {
            IOUtils.copy(fin, response.getOutputStream(), 1024);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
